The R Spatial Ecosystem

“Historical” Packages

  • rgdal: interface between R and GDAL (Geospatial Data Abstraction Library) and PROJ4 libraries: raster / vector geospatial data formats and coordinate transformation.

  • sp: classes and methods for spatial data in R.

  • rgeos: interface between R and GEOS (Geometry Engine - Open Source) library: area, perimeter, distances, dissolve, buffer, overlap, union, contains…

These packages are still widely used.

Simple Features for R

  • sf Website: Simple Features for R

  • First release: October 20, 2016

  • sp, rgeos and rgdal functionnalities in one package.

  • Easier data handling, simpler objects.

  • Tidy data: compatibility with the pipe synthax and tidyverse operators.

  • Main author and maintainer: Edzer Pebesma (also sp author)


sf objects data structure:

format sf

Using sf

Data Import

Reading layer `martinique' from data source `C:\Users\Kim Antunez\Desktop\satRdays\satRday\lecture\data\mtq\martinique.shp' using driver `ESRI Shapefile'
Simple feature collection with 34 features and 23 fields
geometry type:  POLYGON
dimension:      XY
bbox:           xmin: 690574.4 ymin: 1592426 xmax: 736126.5 ymax: 1645660
epsg (SRID):    32620
proj4string:    +proj=utm +zone=20 +datum=WGS84 +units=m +no_defs

Projection

Get current crs with epsg code and change projection with st_transform.

Coordinate Reference System:
  EPSG: 32620 
  proj4string: "+proj=utm +zone=20 +datum=WGS84 +units=m +no_defs"

Data Display

Default

Only geometry

Distance Matrix

Units: [m]
          [,1]     [,2]      [,3]      [,4]      [,5]
[1,]     0.000 35297.56  3091.501 12131.617 17136.310
[2,] 35297.557     0.00 38332.602 25518.913 18605.249
[3,]  3091.501 38332.60     0.000 15094.702 20226.198
[4,] 12131.617 25518.91 15094.702     0.000  7177.011
[5,] 17136.310 18605.25 20226.198  7177.011     0.000

Other Packages

CRAN task views aim to provide some guidance which packages on CRAN are relevant for tasks related to a certain topic.

CRAN Task View: Analysis of Spatial Data:

  • Classes for spatial data
  • Handling spatial data
  • Reading and writing spatial data
  • Visualisation
  • Point pattern analysis
  • Geostatistics
  • Disease mapping and areal data analysis
  • Spatial regression
  • Ecological analysis

Maps with R

Overview

Several solutions are available:

  • ggplot2 users can have a look to ggplot2 mapping features (geom_sf) that can mix nicely with ggspatial.
  • For more advanced mapping features in a ggplot2-like syntax have a look to tmap
  • cartography is based on base graphics and allow most of basic and advanced cartographic representations.
    Full disclosure: one of the speakers is the maintainer of cartography.
  • mapview, leaflet and mapdeck for interactive webmaps.

Here we will focus on cartography and do small examples with ggplot2, tmap, leaflet and mapview.

cartography

Data Preparation

library(sf)
library(dplyr)
# Import geo layers
## Communes of Seine Maritime
sm <- st_read(dsn = "data/dep76/seine_maritime.geojson", stringsAsFactors = F, quiet=TRUE)
## French departements
dep <- st_read(dsn = "data/dep76/dep.geojson", stringsAsFactors = F, quiet=TRUE)

# change projection (lambert93)
sm <- st_transform(sm, 2154)
dep <- st_transform(dep, 2154)

# Import dataset  
csp <- read.csv("data/dep76/data_seine_maritime.csv")
# merge geolayer and dataset
sm <- merge(sm, csp, by="INSEE_COM", all.x=TRUE)

# Prepare some additional contextual informations
# Extract label of main cities
cities = c("Rouen","Fécamp","Le Havre","Dieppe","Le Tréport")
labels = sm %>% filter(LIBELLE %in% cities)

library(osmdata)
# Get major roads from osm
bb      <- sm %>% st_transform(4326) %>% st_bbox()
q       <- opq(bbox = bb,timeout = 180)
qm      <- add_osm_feature (q, key = 'highway',value = 'motorway',value_exact = FALSE)
qt      <- add_osm_feature (q, key = 'highway',value = 'trunk',value_exact = FALSE)
qp      <- add_osm_feature (q, key = 'highway',value = 'primary',value_exact = FALSE)

motorway<- osmdata_sf(qm)
trunk   <- osmdata_sf(qt)
primary <- osmdata_sf(qp)

roads    <- c(primary,trunk,motorway)$osm_lines %>% st_transform(st_crs(sm))
roads.geom = st_intersection(st_geometry(roads),sm) 

# Get the shape of the main river "La seine" 
qr    <- q %>% add_osm_feature (key = 'waterway') %>% add_osm_feature(key="name:fr",value="La Seine")
river <- osmdata_sf(qr)
river.geom <- st_geometry(river$osm_lines %>% filter(name.fr=="La Seine")) %>%
  st_transform(st_crs(sm))

Choropleth Map

We could create the same map on a cartogram based on the active population stock.

Gridded Map

These maps may allow to hide or, at least, diminish the MAUP.

It is also possible to create hexagonal grids.

Smoothed Map

smoothLayer() uses functions from package SpatialPosition to compute Stewart’s potentials of population.
The computation of potentials could be considered as a spatial interpolation method such as inverse distance weighted interpolation (IDW) or kernel density estimator. These models aim to estimate unknown values of non-observed points from known values given by measured points. Cartographically speaking, they are often used to get a continuous surface from a set of discrete points. However, Stewart model is mainly a spatial interaction modeling approach, with a possible secondary use for spatial interpolation.

Cheat Sheet

The cheat sheet displays a quick overview of cartography’s main features:

cartography cheat sheet

ggplot2 and tmap

ggplot2

Proportional symbols layer

Choropleth layer

tmap

TODO Timothée

mapview and leaflet

Proportional symbols layer

These interactive maps, as appealing as they seem to be, are not really suitable for presenting geostatistical information. For porportional symbols both leaflet and mapview lack a proper way to build lengends. Nonetheless, they can be really useful for exploratory data analysis. Both librairies are quite similar with some advantage for mapview (e.g the possibility to render to canvas for bigger datasets) and some other for leaflet (e.g using a customized projection different from web-meractor)

With leaflet data must be provided in long/lat (st_transform(4326)) and will be converted by default to the webmercator coordinate reference system (CRS). You may choose between circles with radius specified in meters (addCircle) or in pixels (addCircleMarkers). If specified in pixel, the radius will stay the same whatever the zoom level is. If specified in meters, it will evolve with zoom level.

Gridded Map

mapview and leaflet enable the use and styling of sf polygons. We may for example reuse the grid built previously to show the share of managers in Seine-Maritime. Default choropleth can be obtained with just three arguments with mapview.

leaflet enables fine tuning of the color scale and legend.

Projection

leaflet enables to use other projections than the web-mercator projection for webmaps. You may deal with tiles built with another projection system such as Lambert 93 by defining a custom leaflet crs (see gis.stackexchange resolution-from-wmts-getcapacilities-scaledenomin and mathematics-behind-converting-scale-to-resolution to deal with WMTS tiles). We use this approach here to deal with Hypsometric tints tiles (tiles colors which encode elevation) and the contour lines of chamois and ibex population area provided by the french national office of hunting and wild animals.

epsg2154 <- leafletCRS(crsClass = "L.Proj.CRS", code = "EPSG:2154",
                       proj4def = "+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3
                       +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0
                       +units=m +no_defs",
                       resolution = 4838095.23807/cumprod(c(1,rep(2,15)))*0.00028,
                       origin= c(-357823.2365,7230727.3772)
)

tile_ortho <- "http://tiles.craig.fr/ortho/service?service=WMTS&request=GetTile&version=1.0.0&
layer=ortho_2016&style=normal&tilematrixset=lambert93&format=image%2Fjpeg&tilematrix={z}
&tilerow={y}&tilecol={x}"

tile_mnt <- "http://tiles.craig.fr/mnt/service?service=WMTS&request=GetTile&version=1.0.0&
layer=relief&style=default&tilematrixset=lambert93&format=image%2Fpng&tilematrix={z}&
tilerow={y}&tilecol={x}"

tile_attrib <- "Map data &copy;
<a href='https://www.craig.fr/contenu/1377-flux-tuile-wmswmtstms'> craig / IGN </a>
and <a href='http://www.oncfs.gouv.fr/Cartographie-ru4/Le-portail-
cartographique-de-donnees-ar291'>ONCF</a>"

bouq = read_sf("./data/BOQ_2017_massif_uni/BOQ_2017_massif_uni_L93.shp")
cha = read_sf("./data/CHA_2017_massif_uni/CHA_2017_massif_uni_L93.shp")

leaflet(options = leafletOptions(worldCopyJump = F, crs = epsg2154)) %>%
 # addTiles(urlTemplate = tile_ortho,attribution = tile_attrib) %>% 
  addTiles(urlTemplate = tile_mnt,attribution = tile_attrib) %>% 
  addPolygons(data = bouq %>% st_transform(4326), fillColor = '#50162D',color = '#772A7F',
              fillOpacity = 0.05,opacity = 1, weight = 2.5, dashArray = "3") %>% 
  addPolygons(data = cha %>% st_transform(4326), fillColor = '#88AA00',color = '#CCFF00',
              fillOpacity = 0.05,opacity = 1, weight=2.5, dashArray = "3") %>% 
  setView(2.692174, 45.067230, 4)

reproducibility

Always share your R and packages configuration !

R version 3.5.1 (2018-07-02)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17134)

Matrix products: default

locale:
[1] LC_COLLATE=French_France.1252  LC_CTYPE=French_France.1252   
[3] LC_MONETARY=French_France.1252 LC_NUMERIC=C                  
[5] LC_TIME=French_France.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] leaflet_2.0.2     bindrcpp_0.2.2    mapview_2.6.3     ggplot2_3.1.0    
[5] cartography_2.1.2 dplyr_0.7.6       sf_0.7-2          rmdformats_0.3.5 
[9] knitr_1.21       

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.17      lattice_0.20-35   png_0.1-7        
 [4] class_7.3-14      assertthat_0.2.0  digest_0.6.15    
 [7] mime_0.6          R6_2.2.2          plyr_1.8.4       
[10] stats4_3.5.1      evaluate_0.12     e1071_1.6-8      
[13] highr_0.7         pillar_1.2.3      rlang_0.3.1      
[16] lazyeval_0.2.1    rstudioapi_0.7    miniUI_0.1.1.1   
[19] raster_2.8-4      rmarkdown_1.11.3  labeling_0.3     
[22] webshot_0.5.0     stringr_1.3.1     questionr_0.7.0  
[25] htmlwidgets_1.2   munsell_0.5.0     shiny_1.1.0      
[28] compiler_3.5.1    httpuv_1.4.4.1    xfun_0.3         
[31] pkgconfig_2.0.1   base64enc_0.1-3   rgeos_0.4-2      
[34] htmltools_0.3.6   tidyselect_0.2.5  tibble_1.4.2     
[37] bookdown_0.9      codetools_0.2-15  viridisLite_0.3.0
[40] withr_2.1.2       later_0.7.3       grid_3.5.1       
[43] jsonlite_1.6      spData_0.3.0      satellite_1.0.1  
[46] xtable_1.8-2      gtable_0.2.0      DBI_1.0.0        
[49] magrittr_1.5      units_0.6-2       scales_1.0.0     
[52] stringi_1.1.7     promises_1.0.1    sp_1.3-1         
[55] tools_3.5.1       glue_1.3.0        purrr_0.2.5      
[58] crosstalk_1.0.0   yaml_2.2.0        colorspace_1.3-2 
[61] classInt_0.2-3    bindr_0.1.1